package com.example.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.entity.User;
import com.example.enums.CodeEnum;
import com.example.exception.ServiceException;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @Author 王鹤蒲
 * @Date 2023 08 06
 */
@Component
public class TokenUtils {

    private static IUserService staticIUserService;

    @Autowired
    private IUserService iUserService;

    @PostConstruct
    public void setStaticIUserService() {
        staticIUserService = iUserService;
    }


    public static String genToken(String userId, String sign) {
        return JWT.create().withAudience(userId)
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(sign));
    }

    public static User verifyToken(String token){
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(CodeEnum.NEED_LOGIN.getCode(), "无token，请重新登录");
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new ServiceException(CodeEnum.NEED_LOGIN.getCode(), "token验证失败");
        }
        User user = staticIUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            throw new ServiceException(CodeEnum.NEED_LOGIN.getCode(), "用户不存在，请重新登录");
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(CodeEnum.NEED_LOGIN.getCode(), "token验证失败，请重新登录");
        }
        return user;
    }

}
